import $kt from "@/uni_modules/uniapp-kantboot";
// "/tool-area-web/toolStateArea/getAll"

let result = {};


result.requestStateArea = function () {
    return new Promise((resolve, reject) => {
        $kt.request.send({
            uri: '/tool-area-web/toolStateArea/getAll',
            method: 'POST',
            stateSuccess: (res) => {
                let stateAreaList = res.data;
                for (let i = 0; i < stateAreaList.length; i++) {
                    stateAreaList[i].name = $kt.i18n.zhToGlobal(stateAreaList[i].name, "stateArea");
                }
                // 按照code的unicode排序
                stateAreaList.sort((a, b) => {
                    return a.code.localeCompare(b.code);
                });
                // 保存到缓存
                $kt.storage.set("toolStateArea:all",stateAreaList);
                // 保存成map
                let stateAreaMap = {};
                for (let i = 0; i < stateAreaList.length; i++) {
                    stateAreaMap[stateAreaList[i].code] = stateAreaList[i];
                }
                // 保存到缓存
                $kt.storage.set("toolStateArea:map", stateAreaMap);
                resolve();
            },
            stateFail: (res) => {
                // 如果网络错误
                if (res?.stateCode === "networkError") {
                    uni.showToast({
                        title: "Network Error",
                        icon: "none"
                    });
                }
                reject();
            }
        });
    });
}

result.getAll = function () {
    return $kt.storage.get("toolStateArea:all");
}

result.getMap = function () {
    return $kt.storage.get("toolStateArea:map");
}

/**
 * getNameByCode
 */
result.getNameByCode = function (code) {
    let map = this.getMap();
    if (map&&map[code]) {
        return map[code].name;
    }
    return "";
}

/**
 * getByCode
 */
result.getByCode = function (code) {
    let map = this.getMap();
    if (map && map[code]) {
        return map[code];
    }
    return {};
}


export default result;

